package com.jingdianjichi.project.domain.service.impl;


import com.alibaba.nacos.common.utils.MapUtils;
import com.jingdianjichi.project.common.entity.PageResult;
import com.jingdianjichi.project.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.project.common.enums.SubjectLikedStatusEnum;
import com.jingdianjichi.project.domain.bo.SubjectLikedBo;
import com.jingdianjichi.project.domain.bo.SubjectLikedMessage;
import com.jingdianjichi.project.domain.convert.SubjectLikedBOConverter;
import com.jingdianjichi.project.domain.redis.RedisUtil;
import com.jingdianjichi.project.domain.service.SubjectLikedDomainService;
import com.jingdianjichi.project.infra.basic.entity.SubjectInfo;
import com.jingdianjichi.project.infra.basic.entity.SubjectLiked;
import com.jingdianjichi.project.infra.basic.service.SubjectInfoService;
import com.jingdianjichi.project.infra.basic.service.SubjectLikedService;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.DocIDMerger;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 题目点赞表 领域service实现了
 *
 * @author jingdianjichi
 * @since 2024-01-07 23:08:45
 */
@Service
@Slf4j
public class SubjectLikedDomainServiceImpl implements SubjectLikedDomainService {

    @Resource
    private SubjectLikedService subjectLikedService;

    @Resource
    private RedisUtil redisUtil;

    private static  final String SUBJECT_LIKED_KEY="subjcet:liked";


    private static final String SUBJECT_LIKED_COUNT_KEY="subject.liked.count";

    private static final String SUBJECT_LIKED_DETAIL_KEY="subject.liked.detail";
    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void  add(SubjectLikedBo subjectLikedBO)
    {
        Long subjcetId =subjectLikedBO.getSubjectId();

        String likeUserId=subjectLikedBO.getLikeUserId();

        Integer status =subjectLikedBO.getStatus();

        //String hashKey = buildSubjectLikedKey(subjcetId.toString(),likeUserId);

        //redisUtil.putHash(SUBJECT_LIKED_KEY,hashKey,status);

        SubjectLikedMessage subjectLikedMessage = new SubjectLikedMessage();
        subjectLikedMessage.setSubjectId(subjcetId);
        subjectLikedMessage.setLikedUserId(likeUserId);
        subjectLikedMessage.setStatus(status);

        rocketMQTemplate.convertAndSend("subject-liked",subjectLikedMessage);

        String countKey= SUBJECT_LIKED_COUNT_KEY+"."+subjcetId;

        String detailKey =SUBJECT_LIKED_DETAIL_KEY+"."+subjcetId+"."+likeUserId;

        if(SubjectLikedStatusEnum.LIKED.getCode()==status)
        {
            redisUtil.increment(countKey,1);

            redisUtil.set(detailKey,"1");
        }
        else {
            Integer count = redisUtil.getInt(countKey);
            if(count>0)
            {
                redisUtil.increment(countKey,-1);
                redisUtil.del(detailKey);
            }
            else return ;
        }

    }

    @Override
    public Boolean isLiked(String subjectId, String userId) {
        String detailKey =SUBJECT_LIKED_DETAIL_KEY+"."+subjectId+"."+userId;
        return redisUtil.exist(detailKey);
    }

    @Override
    public Integer getLikedCount(String subjectId)
    {
        String countKey= SUBJECT_LIKED_COUNT_KEY+"."+subjectId;

        Integer count = redisUtil.getInt(countKey);

        if(count==null||count<0)
        {
            return 0;
        }

        return count;
    }



    private String buildSubjectLikedKey(String subjectId, String userId)
    {
        return subjectId+":"+userId;
    }

    @Override
    public Boolean update(SubjectLikedBo subjectLikedBO) {
        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);
        return subjectLikedService.update(subjectLiked) > 0;
    }

    @Override
    public Boolean delete(SubjectLikedBo subjectLikedBO) {
        SubjectLiked subjectLiked = new SubjectLiked();
        subjectLiked.setId(subjectLikedBO.getId());
        subjectLiked.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());
        return subjectLikedService.update(subjectLiked) > 0;
    }

    public  void syncLiked()
    {
       Map<Object,Object> subjectLikedMap = redisUtil.getHashAndDelete(SUBJECT_LIKED_KEY);

       if(log.isInfoEnabled()) {
           log.info("subjectLikedMap:{}", subjectLikedMap);
       }

       if(MapUtils.isEmpty(subjectLikedMap))
       {
           return ;
       }

        //批量存入数据库
        List<SubjectLiked> subjectLikedList = new ArrayList<>();

       subjectLikedMap.forEach((key,value)->
        {
            SubjectLiked subjectLiked = new SubjectLiked();

            String[] split = key.toString().split(":");

            String subjectId = split[0];
            String likedUserId = split[1];
            subjectLiked.setSubjectId(Long.valueOf(subjectId));
            subjectLiked.setLikeUserId(likedUserId);
            subjectLiked.setStatus(Integer.valueOf(value.toString()));
            subjectLiked.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

            subjectLikedList.add(subjectLiked);
        });

       subjectLikedService.insertBatch(subjectLikedList);

    }

    public PageResult<SubjectLikedBo> getSubjectLikedPage(SubjectLikedBo subjectLikedBO)
    {
        PageResult<SubjectLikedBo> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectLikedBO.getPageNo());
        pageResult.setPageSize(subjectLikedBO.getPageSize());

        int start = (subjectLikedBO.getPageNo() - 1) * subjectLikedBO.getPageSize();

        SubjectLiked subjectLiked = SubjectLikedBOConverter.INSTANCE.convertBOToEntity(subjectLikedBO);

        int count = subjectLikedService.countByCondition(subjectLiked);

        if(count==0)
        {
            return pageResult;
        }


        List<SubjectLiked> subjectLikedList = subjectLikedService.queryPage(subjectLiked, start, subjectLikedBO.getPageSize());

        List<SubjectLikedBo> subjectLikedBoList = SubjectLikedBOConverter.INSTANCE.convertEntityToBoList(subjectLikedList);

        subjectLikedBoList.forEach(info -> {
            SubjectInfo subjectInfo = subjectInfoService.queryById(info.getSubjectId());
            info.setSubjectName(subjectInfo.getSubjectName());
        });


        pageResult.setTotal(count);
        pageResult.setRecords(subjectLikedBoList);
        return pageResult;
    }
    @Override
    public void syncLikedByMessage(SubjectLikedBo subjectLikedBO)
    {
        //批量存入数据库
        SubjectLiked subjectLiked = new SubjectLiked();

        subjectLiked.setSubjectId(subjectLikedBO.getSubjectId());
        subjectLiked.setLikeUserId(subjectLikedBO.getLikeUserId());
        subjectLiked.setStatus(subjectLikedBO.getStatus());
        subjectLiked.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectLikedService.insert(subjectLiked);
    }
}
